/**
 * Copyright (c) 2015-2017, Henry Yang 杨勇 (gismail@foxmail.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.lambkit.module.upms.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lambkit.core.Attr;
import com.lambkit.core.Lambkit;
import com.lambkit.db.DbPool;
import com.lambkit.db.AbstractDaoService;
import com.lambkit.db.IRowDao;
import com.lambkit.db.sql.Example;
import com.lambkit.module.upms.Upms;
import com.lambkit.module.upms.UpmsConfig;
import com.lambkit.module.upms.row.UpmsPermission;
import com.lambkit.module.upms.row.UpmsUser;
import com.lambkit.module.upms.row.UpmsUserPermission;
import com.lambkit.module.upms.sql.UpmsPermissionSQL;
import com.lambkit.module.upms.sql.UpmsUserPermissionSQL;

import java.util.List;

/**
 * @author yangyong 
 * @website: www.lambkit.com
 * @email: gismail@foxmail.com
 * @date ${date}
 * @version 1.0
 * @since 1.0
 */

public class UpmsUserPermissionService extends AbstractDaoService<UpmsUserPermission> {
	public static UpmsUserPermissionService of() {
		return Lambkit.get(UpmsUserPermissionService.class);
	}
	public IRowDao<UpmsUserPermission> dao() {
		String dbPoolName = Lambkit.config(UpmsConfig.class).getDbPoolName();
		return DbPool.use(dbPoolName).dao(UpmsUserPermission.class);
	}

	public IRowDao<UpmsUserPermission> dao(String dbPoolName) {
		return DbPool.use(dbPoolName).dao(UpmsUserPermission.class);
	}

	public int permission(JSONArray datas, UpmsUser user) {
		for (int i = 0; i < datas.size(); i ++) {
			JSONObject json = datas.getJSONObject(i);
			if (json.getBoolean("checked")) {
				// 新增权限
				UpmsUserPermission upmsUserPermission = new UpmsUserPermission();
				upmsUserPermission.setUserId(user.getUserId());
				upmsUserPermission.setPermissionId(json.getLongValue("id"));
				upmsUserPermission.setType(json.getInteger("type"));
				dao().save(upmsUserPermission);
			} else {
				// 删除权限
				Example upmsUserPermissionExample = UpmsUserPermissionSQL.of()
						.andPermissionIdEqualTo(json.getLongValue("id"))
						.andTypeEqualTo(json.getInteger("type")).example();
				dao().delete(upmsUserPermissionExample);
			}
		}
		return datas.size();
	}

	public int permission(JSONArray datas, Long id) {
		for (int i = 0; i < datas.size(); i ++) {
			JSONObject json = datas.getJSONObject(i);
			if (json.getBoolean("checked")) {
				// 新增权限
				UpmsUserPermission upmsUserPermission = new UpmsUserPermission();
				upmsUserPermission.setUserId(id);
				upmsUserPermission.setPermissionId(json.getLongValue("id"));
				upmsUserPermission.setType(json.getInteger("type"));
				dao().save(upmsUserPermission);
			} else {
				// 删除权限
				Example upmsUserPermissionExample = UpmsUserPermissionSQL.of()
						.andPermissionIdEqualTo(json.getLongValue("id"))
						.andTypeEqualTo(json.getInteger("type")).example();
				dao().delete(upmsUserPermissionExample);
			}
		}
		return datas.size();
	}

	public boolean hasRule(Long userId, Integer ruleid) {
		if(Upms.getApiService().hasRole(userId, 1L)) {
			return true;
		}
		Attr data = Attr.by("userId", userId).set("ruleId", ruleid);
		UpmsUserPermission uup = Upms.getApiService().findFirst("upms.getUserRuleByUserIdAndRuleId", UpmsUserPermission.class, data);
		return uup!=null ? true : false;
	}

	public boolean hasRule(Integer roleid, Integer ruleid) {
		if (roleid == 1) {
			return true;
		}
		Attr data = Attr.by("roleId", roleid).set("ruleId", ruleid);
		UpmsUserPermission uup = Upms.getApiService().findFirst("upms.getUserRuleByRoleIdAndRuleId", UpmsUserPermission.class, data);
		return uup!=null ? true : false;
	}

	public boolean hasRule(Long userId, String permission) {
		Attr data = Attr.by("userId", userId).set("permission", permission);
		UpmsPermission upmsPermission = Upms.getApiService().findFirst("upms.getRuleOfUserIdAndRuleName", UpmsPermission.class, data);
		return upmsPermission!=null ? true : false;
	}

	public boolean lacksRule(String permission) {
		Example upc = UpmsPermissionSQL.of().andPermissionValueEqualTo(permission).example();
		UpmsPermission upmsPermission = Lambkit.get(UpmsPermissionService.class).dao().findFirst(upc);
		if(upmsPermission==null || upmsPermission.getStatus()==UpmsPermission.STATUS_LOCK) {
			return false;
		}
		return true;
	}

	public Boolean hasAnyRules(Long userid, String permissions) {
		permissions = permissions.startsWith(",") ? permissions.substring(1) : permissions;
		permissions = permissions.endsWith(",") ? permissions.substring(0, permissions.length()-1) : permissions;
		Attr data = Attr.by("userId", userid).set("names", permissions.split(","));
		List<UpmsPermission> rules = Upms.getApiService().find("upms.getRuleOfUserIdAndRuleNames", UpmsPermission.class, data);
		return rules != null && rules.size() > 0 ? true : false;
	}

	public Boolean hasAllRules(Long userid, String permissions) {
		permissions = permissions.startsWith(",") ? permissions.substring(1) : permissions;
		permissions = permissions.endsWith(",") ? permissions.substring(0, permissions.length()-1) : permissions;
		Attr data = Attr.by("userId", userid).set("names", permissions.split(","));
		List<UpmsPermission> rules = Upms.getApiService().find("upms.getRuleOfUserIdAndRuleNames", UpmsPermission.class, data);
		permissions = "," + permissions + ",";
		if(rules!=null && rules.size() > 0) {
			for (UpmsPermission rule : rules) {
				permissions.replace(","+rule.getName()+",", ",");
			}
			if(",".equals(permissions)) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}
}
